package com.xinlong.shop.api.promotion;

import cn.hutool.core.util.NumberUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xinlong.shop.core.promotion.entity.DetailStatusEnum;
import com.xinlong.shop.core.promotion.entity.PutSaleOrder;
import com.xinlong.shop.core.promotion.entity.RushPurchaseDetail;
import com.xinlong.shop.core.promotion.entity.RushPurchaseDetailQueryParam;
import com.xinlong.shop.core.promotion.entity.dto.RushPurchaseDetailDTO;
import com.xinlong.shop.core.promotion.service.IPutSaleOrderService;
import com.xinlong.shop.core.promotion.service.IRushPurchaseDetailService;
import com.xinlong.shop.framework.common.R;
import com.xinlong.shop.framework.service.ISysSettingService;
import io.swagger.annotations.Api;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author Sylow
 * @Description 抢购订单前端控制器
 * @Date: Created in 10:51 2023/5/4
 */
@RestController
@Api(tags = "抢购订单管理")
@Validated      // get请求验证参数时需要
@RequestMapping("/promotion/rush-purchase/order")
public class RushPurchaseOrderController {
    private final IRushPurchaseDetailService rushPurchaseDetailService;
    private final ISysSettingService sysSettingService;
    private final IPutSaleOrderService putSaleOrderService;

    public RushPurchaseOrderController(IRushPurchaseDetailService rushPurchaseDetailService, ISysSettingService sysSettingService, IPutSaleOrderService putSaleOrderService) {
        this.rushPurchaseDetailService = rushPurchaseDetailService;
        this.sysSettingService = sysSettingService;
        this.putSaleOrderService = putSaleOrderService;
    }

    @RequestMapping(value = "/page", method = RequestMethod.GET)
    public R page(Integer current, Integer size, RushPurchaseDetailQueryParam rushPurchaseDetailQueryParam) {
        IPage<RushPurchaseDetail> page = new Page<>(current, size);
        // 不显示未购买的
        rushPurchaseDetailQueryParam.setFilterStatus(DetailStatusEnum.NOT_BUY.getCode());
        rushPurchaseDetailQueryParam.setSortName("buy_time");
        page = this.rushPurchaseDetailService.findPageByParam(page, rushPurchaseDetailQueryParam);
        return R.success("操作成功", page);
    }

    /**
     * 订单汇总信息
     * @return
     */
    @RequestMapping(value = "/order-summary", method = RequestMethod.GET)
    public R orderSummary() {
        long allOrder = this.rushPurchaseDetailService.countByStatus(null);
        long notBuyOrder = this.rushPurchaseDetailService.countByStatus(DetailStatusEnum.NOT_BUY.getCode());
        long buyOrder = this.rushPurchaseDetailService.countByStatus(DetailStatusEnum.BUY.getCode());
        long payOrder = this.rushPurchaseDetailService.countByStatus(DetailStatusEnum.PAY.getCode());
        long confirmOrder = this.rushPurchaseDetailService.countByStatus(DetailStatusEnum.CONFIRM.getCode());
        long putSaleOrder = this.rushPurchaseDetailService.countByStatus(DetailStatusEnum.PUT_SALE.getCode());
        long cancelOrder = this.rushPurchaseDetailService.countByStatus(DetailStatusEnum.CANCEL.getCode());
        Map<String, Object> result = new HashMap<>();
        result.put("allOrder", allOrder);
        result.put("notBuyOrder", notBuyOrder);
        result.put("buyOrder", buyOrder);
        result.put("payOrder", payOrder);
        result.put("confirmOrder", confirmOrder);
        result.put("putSaleOrder", putSaleOrder);
        result.put("cancelOrder", cancelOrder);

        return R.success("操作成功", result);
    }

    @RequestMapping(value = "/cancel", method = RequestMethod.PUT)
    public R cancel(Integer id) {
        if(id == null || id <= 0) {
            R.error("参数错误");
        }
        this.rushPurchaseDetailService.cancelOrder(id);
        return R.success("操作成功");
    }

    /**
     * 确认收款
     */
    @RequestMapping(value = "/confirm-receipt", method = RequestMethod.PUT)
    public R confirmReceipt(Integer id) {
        if(id == null || id <= 0) {
            R.error("参数错误");
        }
        this.rushPurchaseDetailService.confirmReceipt(id);
        return R.success("操作成功");
    }

    @RequestMapping(value = "/put-sale-info", method = RequestMethod.GET)
    public R putSaleInfo(@NotNull(message = "抢购订单ID不能为空") Integer id) {
        RushPurchaseDetailDTO pd = rushPurchaseDetailService.findDTOById(id);
        // 检查抢购状态
        if (pd.getStatus() != DetailStatusEnum.CONFIRM.getCode()) {
            return R.error("状态不正确");
        }
        /**
         * 这里代码与买家API代码重复 可优化
         */
        // 获取系统配置
        Map<String, Object> setting = sysSettingService.getSetting();
        Double priceMarkup = (Double) setting.get("priceMarkup");
        Double putSalePrice = (Double) setting.get("putSalePrice");

        BigDecimal sellPrice = getPrice(pd.getPrice(), priceMarkup);
        // 服务费是购买的价格来计算
        BigDecimal priceService = getServicePrice(pd.getPrice(), putSalePrice);


        // 设置费用精度
        sellPrice = sellPrice.setScale(0, BigDecimal.ROUND_HALF_UP);
        priceService = priceService.setScale(0, BigDecimal.ROUND_HALF_UP);

        Map<String, Object> result = new HashMap<>();
        result.put("sellPrice", sellPrice);
        result.put("priceService", priceService);

        return R.success(result);
    }


    @RequestMapping(value = "/put-sale", method = RequestMethod.PUT)
    public R putSale(@NotNull(message = "抢购订单ID不能为空") Integer id, @NotNull(message = "销售价格不能为空") BigDecimal price) {
        RushPurchaseDetailDTO pd = rushPurchaseDetailService.findDTOById(id);
        // 检查抢购状态
        if (pd.getStatus() != DetailStatusEnum.CONFIRM.getCode()) {
            return R.error("状态不正确");
        }
        /**
         * 这里代码与买家API代码重复 可优化
         */
        // 获取系统配置
        Map<String, Object> setting = sysSettingService.getSetting();
        Double priceMarkup = (Double) setting.get("priceMarkup");
        Double putSalePrice = (Double) setting.get("putSalePrice");

        BigDecimal sellPrice = getPrice(pd.getPrice(), priceMarkup);
        int flag = price.compareTo(sellPrice);
        // 如果手动价格小于 就使用手动价格，否则使用最高价格
        if (flag == -1 || flag == 0) {
            sellPrice = price;
        }
        // 服务费是购买的价格来计算
        BigDecimal priceService = getServicePrice(pd.getPrice(), putSalePrice);


        // 设置费用精度
        sellPrice = sellPrice.setScale(0, BigDecimal.ROUND_HALF_UP);
        priceService = priceService.setScale(0, BigDecimal.ROUND_HALF_UP);

        PutSaleOrder order = new PutSaleOrder();
        order.setOrderSn(pd.getOrderSn());
        order.setOriginalPrice(pd.getPrice());
        order.setNewPrice(sellPrice);
        order.setServicePrice(priceService);
        order.setRushPurchaseDetailId(pd.getId());
        order.setRushPurchaseId(pd.getRushPurchaseId());
        order.setMemberId(pd.getBuyerId());

        // 保存上架单
        boolean result = this.putSaleOrderService.savePutSaleOrder(order);
        if (result) {
            // 人工上架
            putSaleOrderService.putSaleOrder(order.getOrderSn(), "");
            return R.success();
        } else {
            return R.error();
        }
    }

    /**
     * 获取新上架价格
     * @param price 原价
     * @param priceMarkup 涨幅
     * @return
     */
    private BigDecimal getPrice(BigDecimal price, Double priceMarkup){

        // 配置中是整数 需要除以100
        Double divisor = 100D;
        priceMarkup = NumberUtil.div(priceMarkup, divisor, 3);

        // 新价格= 原价+原价*增幅百分比
        price = NumberUtil.add(price,NumberUtil.mul(price, priceMarkup));


        return price;
    }

    /**
     * 获取服务费金额
     * @param price 商品价格
     * @param putSalePrice 服务费百分比
     * @return
     */
    private BigDecimal getServicePrice(BigDecimal price, Double putSalePrice){

        // 配置中是整数 需要除以100
        Double divisor = 100D;
        putSalePrice = NumberUtil.div(putSalePrice, divisor, 3);

        // 服务费=新价格*百分比
        BigDecimal servicePrice = NumberUtil.mul(price, putSalePrice);

        return servicePrice;
    }

}
